var sel_pmt_obj = null;
var pmtDetail_tabview = null;
function open_sel_pmt(pmtnumber){
	open_pmt_detail(pmtnumber)
}

function open_pmt_detail(pmtnumber){
	from_search = false;
	u_hideAllSections();
	u_safeShowElement('pmtdetails_div');
	
	sel_pmt_obj = null;
	if(pmtDetail_tabview == null){
		pmtDetail_tabview = new YAHOO.widget.TabView("pmtdetails_div_inner");
	}
	
	pmtDetail_tabview.set('activeIndex',0);
	
	if(search_found_cache && search_found_cache != null && search_found_cache.documentType == "PMT"){
		for(var i=0;i<search_found_cache.length;i++){
			if(search_found_cache[i].paymentNumber == pmtnumber){
				sel_pmt_obj = search_found_cache[i];
				from_search = true;
				break;
			}
		}
	}
	
	try{
		if(sel_pmt_obj == null){
			if(pmt_sent_cache && pmt_sent_cache != null && pmt_sent_cache.length > 0){
				for(var i=0;i<pmt_sent_cache.length;i++){
					if(pmtnumber == pmt_sent_cache[i].paymentNumber){
						sel_pmt_obj = pmt_sent_cache[i];
						assignAttachmentComponent("attachmentComponetPlaceHolder7");
						assignCommentsComponent("commentComponetPlaceHolder7");
						 break;
					}
					
				}
			}
		}
	}catch(ex){
	}
	
	try{
		if(sel_pmt_obj == null){
			if(pmt_recd_cache && pmt_recd_cache != null && pmt_recd_cache.length > 0){
				for(var i=0;i<pmt_recd_cache.length;i++){
					if(pmtnumber == pmt_recd_cache[i].paymentNumber){
						sel_pmt_obj = pmt_recd_cache[i];
						 break;
					}
				}
			}
		}
	}catch(ex){}
	
	if(pmt_sent_cache && pmt_sent_cache != null){
		for(var i=0;i<pmt_sent_cache.length;i++){
			if(sel_pmt_obj.paymentNumber == pmt_sent_cache[i].paymentNumber){
				$("pmt_updateAction").style.display = "block";
				assignAttachmentComponent("attachmentComponetPlaceHolder7");
				assignCommentsComponent("commentComponetPlaceHolder7");
				dwr.util.setValue('target_comp_comment',"UPDATE_PMT");
				dwr.util.setValue('target_comp_attachment',"UPDATE_PMT");
				$("attph4_hdr").style.display = "block";
				$("attcm4_hdr").style.display = "block";
				break;
			} else{
				$('attachmentComponent').style.display='none';
				$('commentsComponent').style.display='none';
				$("pmt_updateAction").style.display = "none";
				$("attph4_hdr").style.display = "none";
				$("attcm4_hdr").style.display = "none";
			}
		}
	}else{
		$('attachmentComponent').style.display='none';
		$('commentsComponent').style.display='none';
		$("pmt_updateAction").style.display = "none";
		$("attph4_hdr").style.display = "none";
		$("attcm4_hdr").style.display = "none";
	}
	
	populate_payment_details(sel_pmt_obj);
	
	if(!isNavigationFromBackButton){
		
		var functionPointerObj = new Object();
		functionPointerObj.functionName = "open_pmt_detail("+"'"+pmtnumber+"'"+")";
		navigationStateArray.push(functionPointerObj);
	}
	
}

function populate_payment_details(sel_pmt_obj){
	dwr.util.setValue('pmtdetails_num',"");
	dwr.util.setValue('pmtdetails_date',"");
	dwr.util.setValue('pmtdetails_amt',"");
	dwr.util.setValue('pmt_buyer_name',"");
	dwr.util.setValue('pmt_supp_name',"");
	dwr.util.setValue('pmtdetails_checkbank',"");
	dwr.util.setValue('pmtdetails_checkdate',"");
	dwr.util.setValue('pmtdetails_checknum',"");
	dwr.util.setValue('pmtdetails_checkamt',"");
	dwr.util.setValue('pmtdetails_eftbank',"");
	dwr.util.setValue('pmtdetails_eftacctnum',"");
	dwr.util.setValue('pmtdetails_eftroutingnum',"");
	dwr.util.setValue('pmtdetails_eftamt',"");
	
	if(sel_pmt_obj && sel_pmt_obj != null){
		dwr.util.setValue('pmtdetails_num',sel_pmt_obj.paymentNumber);
		dwr.util.setValue('pmtdetails_date',format_date(sel_pmt_obj.paymentDate));
		dwr.util.setValue('pmtdetails_amt',sel_pmt_obj.totalPaymentAmount);
		dwr.util.setValue('pmt_buyer_name',sel_pmt_obj.paymentFromCompanyName);
		dwr.util.setValue('pmt_supp_name',sel_pmt_obj.paymentToCompanyName);
		if(sel_pmt_obj.methodOfPayment == "CHECK"){
			$('check_pmt_details').style.display = 'block';
			$('eft_pmt_details').style.display = 'none';
			dwr.util.setValue('pmtdetails_checknum',sel_pmt_obj.checkNumber);
			dwr.util.setValue('pmtdetails_checkbank',sel_pmt_obj.checkBankName);
			dwr.util.setValue('pmtdetails_checkdate',format_date(sel_pmt_obj.checkDate));
			dwr.util.setValue('pmtdetails_checkamt',sel_pmt_obj.checkAmount);
		}else if(sel_pmt_obj.methodOfPayment == "EFT"){
			$('check_pmt_details').style.display = 'none';
			$('eft_pmt_details').style.display = 'block';
			dwr.util.setValue('pmtdetails_eftbank',sel_pmt_obj.eftBankName);
			dwr.util.setValue('pmtdetails_eftacctnum',sel_pmt_obj.eftAccountNumber);
			dwr.util.setValue('pmtdetails_eftroutingnum',sel_pmt_obj.eftRoutingNumber);
			dwr.util.setValue('pmtdetails_eftamt',sel_pmt_obj.eftAmount);
		}
		
		populate_attachmentForSelectedPMT(sel_pmt_obj);
		populate_commentsForSelectedPMT(sel_pmt_obj);
		populate_invoiceForSelectedPMT(sel_pmt_obj);
		//Get history of the payment
		populate_pmth_table(sel_pmt_obj.paymentHistory);
	}
		
}

function populate_attachmentForSelectedPMT(pmt){
	try{
	dwr.util.removeAllRows("pmtDisplayattachments_tbody", {
		filter : function(tr) {
			return (tr.id != "pmtDisplayattachments_pattern");
		}
	});	
	if(pmt.paymentAttachmentIds != null){
	
		for(var i=0;i<pmt.paymentAttachmentIds.length;i++){
			var responseText = pmt.paymentAttachmentIds[i];
			var ids = i + ""
			dwr.util.cloneNode('pmtDisplayattachments_pattern', {idSuffix : ids});
			$("pmtDispalyattachments_link"+ids).setAttribute("href",'javascript:openAttachmentPanel("http://www.atsocii.com'+responseText.split(":")[1]+'");');
			$("pmtDispalyattachments_link"+ids).innerHTML = responseText.split(":")[3];
			$("pmtDisplayattachments_pattern"+ids).style.display = '';
		}
	}
	}catch(ex){}
}

function populate_commentsForSelectedPMT(pmt){
	
	try{
		dwr.util.removeAllRows("pmtDisplaycomments_tbody", {
			filter : function(tr) {
				return (tr.id != "pmtDisplaycomments_pattern");
			}
		});
		
		if(pmt.paymentComments != null){
		
			for(var i=0;i<pmt.paymentComments.length;i++){
				var responseText = pmt.paymentComments[i];
				var ids = i + ""
				dwr.util.cloneNode('pmtDisplaycomments_pattern', {idSuffix : ids});
				$("pmtDisplaycomment_text"+ids).innerHTML = responseText;
				$("pmtDisplaycomments_pattern"+ids).style.display = '';
			}
		}
		}catch(ex){}
}

function populate_invoiceForSelectedPMT(pmt){
	try{
	create_invoiceForSelectedPMT();
	clear_invoiceForSelectedPMT();
	var slectedInvoiceArray = pmt.invoices;
	var slectedInvoiceObjectArray = new Array();
	for(var i=0;i<slectedInvoiceArray.length;i++){
		var invoiceID = slectedInvoiceArray[i];
		if(inv_recdcache && inv_recdcache != null){
			for(var j=0;j<inv_recdcache.length;j++){
				if(invoiceID == inv_recdcache[j].invoiceNumber){
					slectedInvoiceObjectArray.push(inv_recdcache[j]);
				}
			}
		}
		
		if(invsent_cache && invsent_cache != null){
			for(var k=0;k<invsent_cache.length;k++){
				if(invoiceID == invsent_cache[k].invoiceNumber){
					slectedInvoiceObjectArray.push(invsent_cache[k]);
				}
			}
		}
	}
	
	invoiceForSelectedPMT_yui_table_instance.addRows(slectedInvoiceObjectArray);
	} catch(ex){
		create_invoiceForSelectedPMT();
		clear_invoiceForSelectedPMT();
	}
}
var invoiceForSelectedPMT_yui_table_instance = null;
function create_invoiceForSelectedPMT() {
	if(invoiceForSelectedPMT_yui_table_instance == null){
	var invrcolumnDefs = [ {
		key : "invoiceNumber",
		label : "Invoice#",
		sortable : true,
		formatter : "hlinkFormatter"
	}, {
		key : "supplierNameText",
		label : "Supplier",
		sortable : true
	}, {
		key : "invoiceSubmittedDate",
		label : "Invoice Date",
		formatter: "date",
		sortable : true
	} , {
		key : "purchaseOrderNumber",
		label : "PO#"
	}, {
		key : "totalInvoiceAmount",
		label : "Amount",
		formatter: "currency"
	} ];

	var invrDataSource = new YAHOO.util.DataSource();
	invrDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
	
	
	invoiceForSelectedPMT_yui_table_instance = new YAHOO.widget.DataTable("pmtdetails_invoice_yui_table",invrcolumnDefs,invrDataSource,{});
	invoiceForSelectedPMT_yui_table_instance.set("selectionMode", "single");
	invoiceForSelectedPMT_yui_table_instance.subscribe("rowClickEvent",
		invoiceForSelectedPMT_yui_table_instance.onEventSelectRow);
	}

}

function clear_invoiceForSelectedPMT() {
	if (invoiceForSelectedPMT_yui_table_instance != null && invoiceForSelectedPMT_yui_table_instance.getRecordSet() != null && invoiceForSelectedPMT_yui_table_instance.getRecordSet().getLength() > 0) {
		var length = invoiceForSelectedPMT_yui_table_instance.getRecordSet().getLength();
		if (length > 0) {
			invoiceForSelectedPMT_yui_table_instance.deleteRows(0, length);
		}
	}
}

function updatePayment(){
	
	try{
		var poNewAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if($('poattachments_check'+ip+'').checked){
					poNewAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		
		
		
		var poNewCmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if($('pocomment_check'+iq+'').checked){
					poNewCmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		
	}catch(ex){}
	
	var dwrCallMetaData = {
			callback : success_updatepmt,
			exceptionHandler : exception_updatepmt_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

	DWR_Invoice.updatePayment(sel_pmt_obj.paymentNumber,poNewAtchArr,poNewCmtarr,loggedinuser,dwrCallMetaData);
	
}

function success_updatepmt(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			var pmtnum = dwrresp.objRespOrError.paymentNumber;
			if(pmt_sent_cache && pmt_sent_cache != null){
				for(var i=0;i<pmt_sent_cache.length;i++){
					if(pmt_sent_cache[i].paymentNumber == pmtnum){
						pmt_sent_cache[i] = dwrresp.objRespOrError ;
						break;
					}
				}
			}	
			
			if(pmt_recd_cache && pmt_recd_cache != null){
				for(var i=0;i<pmt_recd_cache.length;i++){
					if(pmt_recd_cache[i].paymentNumber == pmtnum){
						pmt_recd_cache[i] = dwrresp.objRespOrError ;
						break;
					}
				}
			}	
			open_sel_pmt(pmtnum);
			alert("Payment Updated.");
		}
	} else{
		alert("Payment could not be Updated. Please try again.");
	}
}

function exception_updatepmt_handler(resp){
	//console.log(resp);
}

var pmth_yui_table_instance = null;
var pmthcolumnDefs = [ {
	key : "paymentNumber",
	label : "Payment#"
}, {
	key : "paymentVersion",
	label : "Payment Version",
	formatter: "hlinkFormatter"	
},{
	key : "paymentToCompanyName",
	label : "Supplier",
	sortable : true
}, {
	key : "lastModifiedDate",
	label : "Last Modified Date",
	formatter: formatLastUpdateDate,
	sortable : true
}, {
	key : "lastModifiedBy",
	label : "Last Modified By",
	formatter: "date",
	sortable : true
} , {
	key : "totalPaymentAmount",
	label : "Payment Amount",
	formatter: "currency"
}];

function create_pmth_results_table() {
	if(pmth_yui_table_instance == null){
		var pmtsDataSource = new YAHOO.util.DataSource();
		pmtsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		pmth_yui_table_instance = new YAHOO.widget.DataTable("pmt_history_yui_table",pmthcolumnDefs,pmtsDataSource,{});
		pmth_yui_table_instance.set("selectionMode", "single");
		pmth_yui_table_instance.subscribe("rowClickEvent",pmth_yui_table_instance.onEventSelectRow);
	}
}

function clear_pmth_results_table() {
	if (pmth_yui_table_instance != null) {
		var length = pmth_yui_table_instance.getRecordSet().getLength();
		if (length > 0) {
			pmth_yui_table_instance.deleteRows(0, length);
		}
	}
}

function populate_pmth_table(history){
	create_pmth_results_table();
	clear_pmth_results_table();
	if(history != undefined && history != null && history.length > 0){
		/*for(var i=0;i<history.length;i++){
			history[i].clientNameText = sel_po_cache.clientNameText;
		}*/
		pmth_yui_table_instance.addRows(history);
	}
}

function getpmtverfrom_cache(ver){
	var ret = null;
	if(sel_pmt_obj.paymentHistory && sel_pmt_obj.paymentHistory != null && sel_pmt_obj.paymentHistory.length > 0){
		for(var idx=0; idx<sel_pmt_obj.paymentHistory.length;idx++){
			if(sel_pmt_obj.paymentHistory[idx].paymentVersion == ver){
				ret = sel_pmt_obj.paymentHistory[idx];
				ret.paymentHistory = sel_pmt_obj.paymentHistory;
				break;
			}
		}
	}
	
	return ret;
}

function open_sel_pmt_ver(ver){
	u_hideAllSections();
	u_safeShowElement('pmtdetails_div');
	if(pmtDetail_tabview == null){
		pmtDetail_tabview = new YAHOO.widget.TabView("pmtdetails_div_inner");
	}
	pmtDetail_tabview.set('activeIndex',0);
	
	sel_pmt_obj = getpmtverfrom_cache(ver);
	
	populate_payment_details(sel_pmt_obj);
	
	if(pmt_sent_cache && pmt_sent_cache != null){
		for(var i=0;i<pmt_sent_cache.length;i++){
			if(sel_pmt_obj.paymentNumber == pmt_sent_cache[i].paymentNumber
					&& sel_pmt_obj.paymentVersion == pmt_sent_cache[i].paymentVersion){
				$("pmt_updateAction").style.display = "block";
				assignAttachmentComponent("attachmentComponetPlaceHolder7");
				assignCommentsComponent("commentComponetPlaceHolder7");
				dwr.util.setValue('target_comp_comment',"UPDATE_PMT");
				dwr.util.setValue('target_comp_attachment',"UPDATE_PMT");
				$("attph4_hdr").style.display = "block";
				$("attcm4_hdr").style.display = "block";
				break;
			} else{
				$('attachmentComponent').style.display='none';
				$('commentsComponent').style.display='none';
				$("pmt_updateAction").style.display = "none";
				$("attph4_hdr").style.display = "none";
				$("attcm4_hdr").style.display = "none";
			}
		}
	}else{
		$('attachmentComponent').style.display='none';
		$('commentsComponent').style.display='none';
		$("pmt_updateAction").style.display = "none";
		$("attph4_hdr").style.display = "none";
		$("attcm4_hdr").style.display = "none";
	}
}

function showasxml_pmt(){
	var data = "";
	if(sel_pmt_obj && sel_pmt_obj != null){
		data = sel_pmt_obj.paymentXml;
	}
	showxmldata(data);
}